<?php
namespace app\system\controller;

use app\common\model\CmsMoudleModel;
use think\Request;

class CmsMoudleController extends BaseController
{

    private $cmsMoudleModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->cmsMoudleModel = new CmsMoudleModel();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $list = $this->cmsMoudleModel->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'CmsMoudleValidate.add');
            if (true !== $result) {
                $this->error($result);
            }
            $data['table_name'] = 'cms_' . $data['table_name'];
            if ($this->cmsMoudleModel->addData($data)) {
                $this->cmsMoudleModel->updateCache();
                $this->success('添加成功！', url('index'));
            } else {
                $this->error($this->cmsMoudleModel->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 修改数据
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'CmsMoudleValidate.edit');
            if (true !== $result) {
                $this->error($result);
            }
            if ($this->cmsMoudleModel->editData($data)) {
                $this->cmsMoudleModel->updateCache();
                $this->success('修改成功！', url('index'));
            } else {
                $this->error($this->cmsMoudleModel->getError());
            }
        }
        $mid  = $this->request->param('mid/d');
        $info = $this->cmsMoudleModel->get($mid);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除数据
     */
    public function del()
    {
        $mid = $this->request->param('mid', 0);
        if ($this->cmsMoudleModel->delData($mid)) {
            $this->cmsMoudleModel->updateCache();
            $this->success('删除成功！');
        } else {
            $this->error($this->cmsMoudleModel->getError());
        }
    }

    /**
     * 更新缓存
     */
    public function updateCache()
    {
        $this->cmsMoudleModel->updateCache();
        $this->success('更新缓存成功！');
    }

}
